package com.zyy.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 *@author zhangyangyang
 *@createTime 2023424 16:54
 *@description 路由规则
 */

@Configuration
public class RoutesConfiguration {


    @Autowired
    private KeyResolver hostAddrKeyResolver;

    @Autowired
    @Qualifier("serviceRateLimiter")
    private RateLimiter serviceRateLimiter;


    @Bean
    public RouteLocator declare(RouteLocatorBuilder builder) {
        //目前只对admin和service提供对外服务
        return builder.routes()
            .route(route -> route
                .order(1)
                .path("/gateway/service/**")
                .filters(f -> f.stripPrefix(1)
                    .requestRateLimiter(limiter-> {
                        limiter.setKeyResolver(hostAddrKeyResolver);
                        limiter.setRateLimiter(serviceRateLimiter);
                        // 限流失败后返回的HTTP status code
                        limiter.setStatusCode(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
                    })
                )
                .uri("lb://service")
            ).route(route -> route
                .order(1)
                .path("/gateway/admin/**")
                .filters(f -> f.stripPrefix(1))
                .uri("lb://admin")
            ).build();
    }
}
